import { useEffect, useRef, useState } from 'react';
import * as THREE from 'three';

function Three() {
  const canvasRef = useRef(null);
  const [score, setScore] = useState(0);
  const [lives, setLives] = useState(3);
  // 触摸控制逻辑
  const touchPos = useRef({ x: 0, y: 0 });
  const isTouching = useRef(false);
  // 游戏对象引用
  const player = useRef(null);
  const coins = useRef([]);
  const scene = useRef(new THREE.Scene());
  const camera = useRef(new THREE.PerspectiveCamera(75, 2, 0.1, 1000));
  const renderer = useRef(null);

  useEffect(() => {
    // 初始化场景
    camera.current.position.set(0, 0, 10);
    renderer.current = new THREE.WebGLRenderer({ 
      antialias: true,
      canvas: canvasRef.current 
    });

    // 创建玩家（接元宝的篮子）
    const createPlayer = () => {
      const geometry = new THREE.BoxGeometry(2, 0.5, 1);
      const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
      player.current = new THREE.Mesh(geometry, material);
      player.current.position.y = -4;
      scene.current.add(player.current);
    };

    // 生成金币
    const spawnCoin = () => {
      const geometry = new THREE.CylinderGeometry(0.5, 0.5, 0.2, 32);
      const material = new THREE.MeshBasicMaterial({ color: 0xFFD700 });
      const coin = new THREE.Mesh(geometry, material);
      coin.position.x = Math.random() * 8 - 4; // X轴随机位置
      coin.position.y = 5;
      scene.current.add(coin);
      coins.current.push(coin);
    };

    // 碰撞检测
    const checkCollision = (coin) => {
      const playerBox = new THREE.Box3().setFromObject(player.current);
      const coinBox = new THREE.Box3().setFromObject(coin);
      return playerBox.intersectsBox(coinBox);
    };

    // 游戏循环
    const animate = () => {
      requestAnimationFrame(animate);
      
      // 移动金币
      coins.current.forEach((coin, index) => {
        coin.position.y -= 0.1;
        
        // 碰撞检测
        if (checkCollision(coin)) {
          scene.current.remove(coin);
          coins.current.splice(index, 1);
          setScore(s => s + 10);
        }

        // 移除超出屏幕的金币
        if (coin.position.y < -5) {
          scene.current.remove(coin);
          coins.current.splice(index, 1);
          setLives(l => Math.max(0, l - 1)); // 确保不会减到负数
        }
      });

      // 随机生成金币
      if (Math.random() < 0.02) {
        spawnCoin();
      }

      renderer.current.render(scene.current, camera.current);
    };


    

    const handleTouchStart = (e) => {
      isTouching.current = true;
      const touch = e.touches[0];
      touchPos.current = {
        x: touch.clientX,
        y: touch.clientY
      };
      e.preventDefault(); // 阻止默认滚动行为
    };

    const handleTouchMove = (e) => {
      if (!isTouching.current) return;
      
      const touch = e.touches[0];
      const deltaX = touch.clientX - touchPos.current.x;
      
      // 将屏幕坐标转换为三维坐标
      const mouse = new THREE.Vector2();
      mouse.x = (touch.clientX / window.innerWidth) * 2 - 1;
      mouse.y = -(touch.clientY / window.innerHeight) * 2 + 1;
      
      const raycaster = new THREE.Raycaster();
      raycaster.setFromCamera(mouse, camera.current);
      
      // 计算与地面平面的交点
      const groundPlane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0);
      const intersection = new THREE.Vector3();
      raycaster.ray.intersectPlane(groundPlane, intersection);
      
      // 限制移动范围
      player.current.position.x = THREE.MathUtils.clamp(
        intersection.x,
        -4,
        4
      );

      touchPos.current = {
        x: touch.clientX,
        y: touch.clientY
      };
      e.preventDefault();
    };

    const handleTouchEnd = () => {
      isTouching.current = false;
    };

    // 添加事件监听
    const canvas = canvasRef.current;
    canvas.addEventListener('touchstart', handleTouchStart);
    canvas.addEventListener('touchmove', handleTouchMove);
    canvas.addEventListener('touchend', handleTouchEnd);
    // 玩家控制
    const handleKeyDown = (e) => {
      if (e.key === 'ArrowLeft') {
        player.current.position.x = Math.max(-4, player.current.position.x - 0.5);
      } else if (e.key === 'ArrowRight') {
        player.current.position.x = Math.min(4, player.current.position.x + 0.5);
      }
    };

    createPlayer();
    window.addEventListener('keydown', handleKeyDown);
    animate();

    return () => {
      canvas.removeEventListener('touchstart', handleTouchStart);
      canvas.removeEventListener('touchmove', handleTouchMove);
      canvas.removeEventListener('touchend', handleTouchEnd);
      window.removeEventListener('keydown', handleKeyDown);
      coins.current.forEach(coin => scene.current.remove(coin));
      scene.current.remove(player.current);
    };
  }, []);

  return (
    <div style={{ position: 'relative' }}>
      <canvas ref={canvasRef} style={{ width: '100%', height: '600px' }} />
      
      {/* 游戏UI */}
      <div style={{
        position: 'absolute',
        top: 20,
        left: 20,
        color: 'white',
        fontFamily: 'Arial',
        fontSize: '24px'
      }}>
        <div>得分: {score}</div>
        <div>生命: {'♥'.repeat(Math.max(0, lives))}</div>
      </div>

      {/* 游戏结束提示 */}
      {lives <= 0 && (
        <div style={{
          position: 'absolute',
          top: '50%',
          left: '50%',
          transform: 'translate(-50%, -50%)',
          color: 'red',
          fontSize: '48px',
          fontWeight: 'bold'
        }}>
          游戏结束！
        </div>
      )}
    </div>
  );
}

export default Three